package com.wrl.mmall.controller.common;

import com.wrl.mmall.common.Const;
import com.wrl.mmall.pojo.User;
import com.wrl.mmall.util.CookieUtil;
import com.wrl.mmall.util.JsonUtil;
import com.wrl.mmall.util.RedisShardedPoolUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 设置自定义http请求过滤器，用来重置用户session的时间
 *
 * @author Wang Renlei
 * @Date 2019/10/16 0016
 */
public class SessionExpireFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //首先强转
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if (StringUtils.isNotEmpty(loginToken)) {
            //判断loginToken不为空或不为""
            //符合条件，继续拿user信息

            String userStr = RedisShardedPoolUtil.get(loginToken);
            User user = JsonUtil.stringToObj(userStr, User.class);
            if (user != null) {
                //如果user不为空，则重置session时间，即调用expire
                RedisShardedPoolUtil.expire(loginToken, Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
        //接着需要在web.xml里面加上这个自定义过滤器
    }

    @Override
    public void destroy() {

    }
}
